package com.neo.productitsms.pro.home.view.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.neo.productitsms.R;
import com.neo.productitsms.common.recviewpager.adapter.WebBannerAdapter;
import com.neo.productitsms.common.recviewpager.banner.BannerLayout;
import com.neo.productitsms.config.AppConfig;
import com.neo.productitsms.config.ItsmsApplication;
import com.neo.productitsms.load.GlideImageLoad;
import com.neo.productitsms.pro.base.view.fragment.BaseFragment;
import com.neo.productitsms.pro.home.view.navigation.HomeNaviBar;
import com.neo.productitsms.pro.home.widget.Entity.MenuEntity;
import com.neo.productitsms.pro.home.widget.LineGridView;
import com.neo.productitsms.pro.home.widget.adapter.IndexDataAdapter;
import com.neo.productitsms.pro.home.widget.ui.MenuManageActivity;
import com.neo.productitsms.pro.widget.dialogtip.UIAlertDialog;
import com.neo.productitsms.pro.widget.marquee.MarqueeView;
import com.neo.productitsms.utils.LogUtils;
import com.neo.productitsms.utils.ToastUtil;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * Created by Administrator on 2018/6/27.
 */

public class HomeFragmentBac extends BaseFragment {
    @BindView(R.id.home_banner)
    Banner homeBanner;
    @BindView(R.id.recycler)
    BannerLayout recycler;
    @BindView(R.id.home_marqueeView)
    MarqueeView homeMarqueeView;
    @BindView(R.id.gv_lanuch_start)
    LineGridView gridView;

    private int marqueeNum = 6;


    private static ItsmsApplication appContext;
    //    private LineGridView gridView;
    private List<MenuEntity> indexDataAll = new ArrayList<MenuEntity>();
    private List<MenuEntity> indexDataList = new ArrayList<MenuEntity>();
    private IndexDataAdapter adapter;
    private final static String fileName = "menulist";


    @Override
    public int bindLayoutId() {
        return R.layout.fragment_home;
    }

    @Override
    public void initContentView(View contentView) {
        initLayoutView(contentView);
//        appContext = (ItsmsApplication) getApplication();
        appContext = (ItsmsApplication) ItsmsApplication.getContext();
    }

    private void initLayoutView(View contentView) {

        initNavigation(contentView);


    }

    private void initRecViewPager() {

        List<String> list = new ArrayList<>();
        list.add("http://img0.imgtn.bdimg.com/it/u=1352823040,1166166164&fm=27&gp=0.jpg");
        list.add("http://img3.imgtn.bdimg.com/it/u=2293177440,3125900197&fm=27&gp=0.jpg");
        list.add("http://img3.imgtn.bdimg.com/it/u=3967183915,4078698000&fm=27&gp=0.jpg");
        list.add("http://img0.imgtn.bdimg.com/it/u=3184221534,2238244948&fm=27&gp=0.jpg");
        list.add("http://img4.imgtn.bdimg.com/it/u=1794621527,1964098559&fm=27&gp=0.jpg");
        list.add("http://img4.imgtn.bdimg.com/it/u=1243617734,335916716&fm=27&gp=0.jpg");
        WebBannerAdapter webBannerAdapter = new WebBannerAdapter(getContext(), list);
        webBannerAdapter.setOnBannerItemClickListener(new BannerLayout.OnBannerItemClickListener() {
            @Override
            public void onItemClick(int position) {
                ToastUtil.showShort("点击了第  " + position + "  项");
            }
        });

        recycler.setAdapter(webBannerAdapter);
    }

    private void initNavigation(View contentView) {

//        HomeNavigation.Builder builder = new HomeNavigation.Builder(getContext(), ((ViewGroup) contentView));
//
//
//        builder.setLeftText("注册")
//                .setCenterText(R.string.tab_home_text)
//                .setRightText("登录")
//                .setRightOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
////                        loginPresenter.login();
//
//                        ToastUtil.show("点我");
//                        showOne();
//
//
//                    }
//                });
//
//        builder.create().createAndBind();

        HomeNaviBar homeNaviBar = new HomeNaviBar(getContext());
        homeNaviBar.setOnSearchListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ToastUtil.showShort("搜索点击");
            }
        }).setRightIconOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ToastUtil.showShort("右侧");

            }
        })
                .setRightIcon(R.mipmap.icon_back)
                .createAndBind(((ViewGroup) contentView));

    }


    @Override
    protected void initData() {

        List<Integer> list = new ArrayList<>();
        list.add(R.mipmap.welcome_bg);
        list.add(R.mipmap.welcome_bg);
        list.add(R.mipmap.welcome_bg);
        homeBanner.setImages(list)
                .setImageLoader(new GlideImageLoad())
                .setDelayTime(1500)
                .start();
        homeBanner.updateBannerStyle(BannerConfig.NOT_INDICATOR);

        initRecViewPager();

        initMarqueenData();

        initHomeMenu();
    }

    private void initHomeMenu() {

        gridView.setFocusable(false);
        String strByJson = getJson(getContext(), fileName);

        //Json的解析类对象
        JsonParser parser = new JsonParser();
        //将JSON的String 转成一个JsonArray对象
        JsonArray jsonArray = parser.parse(strByJson).getAsJsonArray();
        Gson gson = new Gson();
        //加强for循环遍历JsonArray
        for (JsonElement indexArr : jsonArray) {
            //使用GSON，直接转成Bean对象
            MenuEntity menuEntity = gson.fromJson(indexArr, MenuEntity.class);
            indexDataAll.add(menuEntity);
        }
        //appContext.delFileData(AppConfig.KEY_All);

        String key = AppConfig.KEY_All;
        String keyUser = AppConfig.KEY_USER;
        appContext.saveObject((Serializable) indexDataAll, AppConfig.KEY_All);

        List<MenuEntity> indexDataUser = (List<MenuEntity>) appContext.readObject(AppConfig.KEY_USER);
        if (indexDataUser == null || indexDataUser.size() == 0) {
            appContext.saveObject((Serializable) indexDataAll, AppConfig.KEY_USER);
        }
        indexDataList = (List<MenuEntity>) appContext.readObject(AppConfig.KEY_USER);

        MenuEntity allMenuEntity = new MenuEntity();
        allMenuEntity.setIco("");
        allMenuEntity.setId("all");
        allMenuEntity.setTitle("全部");
        indexDataList.add(allMenuEntity);
        adapter = new IndexDataAdapter(getContext(), indexDataList);
        gridView.setAdapter(adapter);
        LogUtils.e(strByJson);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent();
                Bundle bundle = new Bundle();
                String title = indexDataList.get(position).getTitle();
                String strId = indexDataList.get(position).getId();
                LogUtils.i(title + strId);
                if (strId.equals("all")) {// 更多
                    intent.setClass(getContext(), MenuManageActivity.class);
                    startActivity(intent);
                }
            }
        });


    }




    public static String getJson(Context context, String fileName) {
        StringBuilder stringBuilder = new StringBuilder();
        try {
            AssetManager assetManager = context.getAssets();
            BufferedReader bf = new BufferedReader(new InputStreamReader(
                    assetManager.open(fileName)));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
            LogUtils.e(e.toString());
        }
        return stringBuilder.toString();
    }

    @Override
    public void onResume() {
        super.onResume();
        indexDataList.clear();
        indexDataList = (List<MenuEntity>) appContext.readObject(AppConfig.KEY_USER);
        MenuEntity allMenuEntity = new MenuEntity();
        allMenuEntity.setIco("all_big_ico");
        allMenuEntity.setId("all");
        allMenuEntity.setTitle("全部");
        indexDataList.add(allMenuEntity);
        adapter = new IndexDataAdapter(getContext(), indexDataList);
        gridView.setAdapter(adapter);
    }


    private void initMarqueenData() {

        /**
         * 设置一个集合
         */
        List<String> info = new ArrayList<>();

        for (int i = 0; i < marqueeNum; i++) {
            info.add(i + ". 滚动条展示 " + i);
        }
        homeMarqueeView.startWithList(info);


    }

    public void showOne() {

        new UIAlertDialog(getActivity()).builder()
                .setMsg("你现在无法接收到新消息提醒。请到系统-设置-通知中开启消息提醒")
                .setCancelable(false)
                .setNegativeButton("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                }).show();

    }

}
